package com.example.moneybook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.moneybook.dto.DetailDto;
import com.example.moneybook.dto.ResponseResult;
import com.example.moneybook.enums.AppHttpCodeEnum;
import com.example.moneybook.mapper.AccountMapper;
import com.example.moneybook.mapper.DetailMapper;
import com.example.moneybook.pojo.Account;
import com.example.moneybook.pojo.Bill;
import com.example.moneybook.pojo.BillDto;
import com.example.moneybook.service.AccountService;
import com.example.moneybook.service.DetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DetailServiceImpl extends ServiceImpl<DetailMapper, Bill> implements DetailService {

    @Autowired
    private DetailMapper detailMapper;

    /**
     * 加载账单明细
     * @param userId
     * @param billDate
     * @return
     * @throws ParseException
     */
    @Override
    public ResponseResult load(String userId,String billDate) throws ParseException {
        //查询当月有记账的所有日期
        List<String> allDate = detailMapper.allDate(userId, billDate);
        List<DetailDto> res = new ArrayList<>();
        //当月的总支出
        int allExp = 0;
        //当月的总收入
        int allIncome = 0;

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String []s={"星期天","星期一","星期二","星期三","星期四","星期五","星期六",};
        for (String str : allDate){
            //当天的总支出
            int exp = 0;
            //当天的总收入
            int income = 0;
            DetailDto detailDto = new DetailDto();
            //查询当天的所有账单记录
            List<BillDto> oneDayBill = detailMapper.oneDay(userId, str);
            for (BillDto bill : oneDayBill){
                if (bill.getState() == 1){
                    exp -= bill.getMoney();
                    allExp -= bill.getMoney();
                }else {
                    income += bill.getMoney();
                    allIncome += bill.getMoney();
                }
            }
            //根据日期判断是星期几
            Date d = dateFormat.parse(str);
            int week = calendar.get(Calendar.DAY_OF_WEEK)-1;
            calendar.setTime(d);

            detailDto.setExpenditure(exp);
            detailDto.setIncome(income);
            detailDto.setTime(str.substring(5,7)+"月"+str.substring(8,str.length())+"日");
            detailDto.setWeek(s[week]);
            detailDto.setList(oneDayBill);
            res.add(detailDto);
        }
        HashMap<String, Object> resMap = new HashMap<>();
        resMap.put("allSpend", allExp);
        resMap.put("allIncome", allIncome);
        resMap.put("list",res);
        return ResponseResult.okResult(resMap);
    }

    @Autowired
    AccountService accountService;
    /**
     * 添加账单
     * @param bill
     * @return
     */
    @Override
    public ResponseResult addDetail(Bill bill, String accountName) {
        if (bill == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        int accountId = accountService.getAccountId(bill.getUserId(), accountName);
        if (!accountName.equals("null") && bill.getState() == 0) {
            Account accountInfo = accountService.getAccountInfo(bill.getUserId(), accountId);
            if (accountInfo.getAccountState() == 1){
                if (accountInfo.getAccountMoney() == 0) {
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "该借贷账户已还清");
                }
                if (accountInfo.getAccountMoney() - bill.getMoney() < 0){
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "该借贷账户偿还金额过多");
                }
            }

        }

        bill.setAccountId(accountId);
        accountService.updateAccountMoney(accountId, bill.getState(), bill.getMoney());

        int res = detailMapper.insert(bill);
        if (res == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }else {
            return ResponseResult.okResult(200,"成功添加一条记录");
        }

    }

    /**
     * 获取某个账户的账单
     * @param userId
     * @param accountId
     * @return
     */
    @Override
    public List<Bill> detailByAccount(String userId, int accountId) {
        QueryWrapper<Bill> billQueryWrapper = new QueryWrapper<>();
        billQueryWrapper
                .eq("user_id",userId)
                .eq("account_id",accountId);
        List<Bill> bills = detailMapper.selectList(billQueryWrapper);
        return bills;
    }

    /**
     * 更改账单
     * @param bill
     * @return
     */
    @Override
    public ResponseResult updateBill(Bill bill, String accountName) {
        if (bill == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        int accountId = accountService.getAccountId(bill.getUserId(), accountName);
        bill.setAccountId(accountId);
        UpdateWrapper<Bill> billUpdateWrapper = new UpdateWrapper<>();
        int i = detailMapper.updateById(bill);
        return ResponseResult.okResult(i);
    }

    /**
     * 删除账单
     * @param userId
     * @param billId
     * @return
     */
    @Override
    public ResponseResult deleteBill(String userId, int billId) {
        QueryWrapper<Bill> queryWrapper = new QueryWrapper();
        queryWrapper
                .eq("bill_id", billId)
                .eq("user_id", userId);
        Bill bill = detailMapper.selectOne(queryWrapper);
        if (bill != null){
            if (bill.getAccountId() != 0){
                System.out.println(bill.getAccountId());
                if (bill.getState() == 0){
                    accountService.updateAccountMoney(bill.getAccountId(), 1, bill.getMoney());
                }else if (bill.getState() == 1){
                    accountService.updateAccountMoney(bill.getAccountId(), 0, bill.getMoney());
                }
            }
        }
        int res = detailMapper.delete(queryWrapper);
        if (res == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "删除失败");
        }else {
            return ResponseResult.okResult(200, "删除成功");
        }
    }

    /**
     * 更新收支信息关联的账户信息
     * @param userId
     * @param accountId
     * @return
     */
    @Override
    public int updateBillByAcc(String userId, int accountId) {
        UpdateWrapper<Bill> billUpdateWrapper = new UpdateWrapper<>();
        billUpdateWrapper
                .eq("user_id", userId)
                .eq("account_id", accountId)
                .set("account_id", 0);
        int res = detailMapper.update(null, billUpdateWrapper);
        return res;
    }
}
